let svgcode;
function getcode() {
  request({
    url: "/v1/codeimg",
    success: res => {
      codeimg.innerHTML = res.data;
      svgcode = res.text;
    },
  });
}
getcode();
codeimg.onclick = () => {
  getcode();
};

$("#loginbtn").on("click", function () {
  if (!username.value) {
    Tip.setTip("请输入用户名!");
  } else if (!password.value) {
    Tip.setTip("请输入密码!");
  } else if (!code.value) {
    Tip.setTip("请输入验证码!");
  }

  if (username.value != "" && password.value != "" && code.value == svgcode) {
    request({
      method: "post",
      url: "/v1/user",
      data: {
        username: username.value,
      },
      success: function (res) {
        // console.log(res);
        if (res.code == 404) {
          Tip.setTip("请输入正确的用户名!");
        }
        if (res.code == 200) {
          // console.log(res.data);

          const user = {
            username: res.data[0].username,
            loginTime: new Date().getTime(),
            userrole: res.data[0].role,
            usertel: res.data[0].usertel,
          };
          if (user.userrole * 2 + 1 != $(".whatrole input:checked").index()) {
            Tip.setTip("发生了错误，请选择正确角色...");
            return;
          }
          if (password.value == res.data[0].password) {
            sessionStorage.setItem("user", JSON.stringify(user));

            if (user.userrole == 0) {
              Tip.setTip("登陆成功,3s后自动跳转", function () {
                location.replace("../../index.html");
              });
              setTimeout(() => {
                location.replace("../../index.html");
              }, 3000);
            } else if (user.userrole == 1) {
              Tip.setTip("登陆成功,3s后自动跳转", function () {
                location.replace("../MemberUsers/MemberUsers.html");
              });
              setTimeout(() => {
                location.replace("../MemberUsers/MemberUsers.html");
              }, 3000);
            } else if (user.userrole == 2) {
              Tip.setTip("登陆成功,3s后自动跳转", function () {
                location.replace("../accessManager/accessManager.html");
              });
              setTimeout(() => {
                location.replace("../accessManager/accessManager.html");
              }, 3000);
            } else if (user.userrole == 3) {
              Tip.setTip("登陆成功,3s后自动跳转", function () {
                location.replace("http://127.0.0.1:8080");
              });
              setTimeout(() => {
                location.replace("http://127.0.0.1:8080");
              }, 3000);
            }
          } else {
            Tip.setTip("密码错误!");
          }
        }
      },
    });
  }

  getcode();
});

$(window).on("keyup", function (e) {
  if (e.keyCode == 13) {
    $("#loginbtn").trigger("click");
  }
});
